package floatWindow2.rom;/*
 * Copyright (C) 2016 Facishare Technology Co., Ltd. All Rights Reserved.
 */

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
import com.example.livesettingtest.MyConstant;
import com.example.livesettingtest.R;
import java.lang.reflect.Method;

import floatWindow2.FloatActionController;
import floatWindow2.RomUtils;

public class MiuiUtils {
    private static final String TAG = "MiuiUtils";
    static Context mContext;

    public static MiuiUtils getInstance(Context context) {
        mContext = context;
        return MiuiUtils.LittleMonkProviderHolder.sInstance;
    }

    // 静态内部类
    private static class LittleMonkProviderHolder {
        private static final MiuiUtils sInstance = new MiuiUtils();
    }


    /**
     * 引导用户打开所有权限
     * @param tipType
     * @param isPermission
     */
    public void openPermission(MyConstant.tipType tipType, boolean isPermission) {


        try
        {
            Intent intent = new Intent();
            ComponentName componentName = null;
            String packName = mContext.getPackageName();
            componentName = new ComponentName("com.miui.securitycenter", "com.miui.appmanager.ApplicationsDetailsActivity");
          //gxw-  componentName = ComponentName.unflattenFromString("com.miui.securitycenter/com.miui.appmanager.ApplicationsDetailsActivity");


            intent.putExtra("package_name", mContext.getPackageName());
            intent.putExtra("package_label", mContext.getString(R.string.app_name));
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);


            //gxw-componentName = new ComponentName("com.miui.appmanager", "ApplicationsDetailsActivity");

            intent.setComponent(componentName);
            mContext.startActivity(intent);
        }
        catch (Exception e)
        {
            Log.i(TAG,"打开权限失败:"+e.getMessage());
            e.printStackTrace();
        }



     /*gxw-原版，系統action打開APP應用管理信息   Intent intent = new Intent();
        intent.setData(Uri.parse("package:" + mContext.getPackageName()));
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //gxw-intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);//打开浮动窗口权限

        try {
            if(tipType == MyConstant.tipType.MI_OPEN_ALL_PERMISSION) {
                Toast toast = Toast.makeText(mContext, R.string.permission_manage,Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
            mContext.startActivity(intent);
            openFloatWindowTip(tipType,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e);
        }*/
        return;
    }
    /**
     * 锁屏后受保护应用
     */
    public void lockScreenProtected(boolean isPermission)
    {
        try {
            Intent intent = new Intent();
            intent.setData(Uri.parse("package:" + mContext.getPackageName()));
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);//打开应用信息管理
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.MI_LOCK_PROTECT,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e);
            e.printStackTrace();
        }
        return;
    }

    public void dealErrorSkip(Exception e) {
        Toast.makeText(mContext, "不兼容", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        Log.i(TAG, e.getMessage());
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        mContext.startActivity(intent);
    }

    public void dealErrorSkip(Exception e,MyConstant.tipType type,boolean permissionFloat) {
        Log.i(TAG, "跳转异常了");
        toastTip(R.string.vivo_settings_permission);
        e.printStackTrace();
        Log.i(TAG, e.getMessage());
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        mContext.startActivity(intent);

        switch (type)
        {
            case VIVO_PERMISSION2:
            case VIVO_PERMISSION:
                openFloatWindowTip(MyConstant.tipType.VIVO_SETTINGS_PERMISSION,permissionFloat);
                break;
        }
    }

    public void toastTip(int tipResId)
    {
        Toast toast = Toast.makeText(mContext,tipResId,Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }




    /**
     * 打开浮动窗口
     */
    static public void openFloatWindowTip( MyConstant.tipType floatWindowType, boolean isPermission) {

        //有对应权限或者系统版本小于7.0
        if (isPermission || Build.VERSION.SDK_INT < 24) {  //gxw:也就是android 6.0及以下，这里需要在6.0以下的手机上测试一下
            //开启悬浮窗
            FloatActionController.getInstance().startMonkServer(mContext,floatWindowType);
        }

        return;
    }

















    /**
     * 检测 miui 悬浮窗权限
     */
    public static boolean checkFloatWindowPermission(Context context) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            return checkOp(context, 24); //OP_SYSTEM_ALERT_WINDOW = 24;
        } else {
//            if ((context.getApplicationInfo().flags & 1 << 27) == 1) {
//                return true;
//            } else {
//                return false;
//            }
            return true;
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class clazz = AppOpsManager.class;
                Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
                return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        } else {
            Log.e(TAG, "Below API 19 cannot invoke!");
        }
        return false;
    }

    /**
     * 小米 ROM 权限申请
     */
    public static void applyMiuiPermission(Context context) {
        int versionCode = getMiuiVersion();
        if (versionCode == 5) {
            goToMiuiPermissionActivity_V5(context);
        } else if (versionCode == 6) {
            goToMiuiPermissionActivity_V6(context);
        } else if (versionCode == 7) {
            goToMiuiPermissionActivity_V7(context);
        } else if (versionCode == 8) {
            goToMiuiPermissionActivity_V8(context);
        } else {
            Log.e(TAG, "this is a special MIUI rom version, its version code " + versionCode);
        }
    }
    public static int getMiuiVersion() {
        String version = RomUtils.getSystemProperty("ro.miui.ui.version.name");
        if (version != null) {
            try {
                return Integer.parseInt(version.substring(1));
            } catch (Exception e) {
                Log.e(TAG, "get miui version code error, version : " + version);
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return -1;
    }
    private static boolean isIntentAvailable(Intent intent, Context context) {
        if (intent == null) {
            return false;
        }
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }

    /**
     * 小米 V5 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V5(Context context) {
        Intent intent = null;
        String packageName = context.getPackageName();
        intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", packageName, null);
        intent.setData(uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "intent is not available!");
        }

        //设置页面在应用详情页面
//        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
//        PackageInfo pInfo = null;
//        try {
//            pInfo = context.getPackageManager().getPackageInfo
//                    (HostInterfaceManager.getHostInterface().getApp().getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            AVLogUtils.e(TAG, e.getMessage());
//        }
//        intent.setClassName("com.android.settings", "com.miui.securitycenter.permission.AppPermissionsEditor");
//        intent.putExtra("extra_package_uid", pInfo.applicationInfo.uid);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (isIntentAvailable(intent, context)) {
//            context.startActivity(intent);
//        } else {
//            AVLogUtils.e(TAG, "Intent is not available!");
//        }
    }

    /**
     * 小米 V6 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V6(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "Intent is not available!");
        }
    }

    /**
     * 小米 V7 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V7(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "Intent is not available!");
        }
    }

    /**
     * 小米 V8 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V8(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
//        intent.setPackage("com.miui.securitycenter");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            intent.setPackage("com.miui.securitycenter");
            intent.putExtra("extra_pkgname", context.getPackageName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (isIntentAvailable(intent, context)) {
                context.startActivity(intent);
            } else {
                Log.e(TAG, "Intent is not available!");
            }
        }
    }
}
